import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import Store from '../store'

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};
Vue.use(VueRouter)
const routes = [
  {
    path:'/',
    redirect:'/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/deatils',
    name: 'deatils',
    component: () => import(/* webpackChunkName: "deat" */ '../views/Deatils.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user') {
    // 当用户想要跳转到 用户/user 页面时
    // 判断用户是否登录  -- 判断token 是否存在
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      // 进行token 的鉴权 然后再去判断是否可以继续跳转
      // 我们这里只判断有没有token
      next()
    } else {
      // 给提示
      let toastObj = {
        content: "请先登录",
        icon: "danger",
      };
      Store.dispatch("AsncToast", toastObj);
      // 打开登录框
      Store.commit('changeIsLogin', true)
    }
    return
  }
  next()
})
export default router
